#ifndef MODEL_H
#define MODEL_H

#include "stb_image.h"
#include "includes/assimp/Importer.hpp"
#include "includes/assimp/scene.h"
#include "includes/assimp/postprocess.h"

#include "mesh.h"
#include "shader.h"

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;


class Model : protected QOpenGLFunctions_3_3_Compatibility
{
public:
    /* render data*/
    int texEnable;
    QVector3D orgColor;
    int drawType;
    int lampType;
    QVector3D lightPos;
    QVector3D cameraPos;
    QVector3D cameraFront;
    int clarkLoop; // 1 : clark; 2 : loop
    // Mesh function 1
    void setupMesh(unsigned int &VAO, unsigned int &VBO, unsigned int &EBO, vector<Vertex> &vertices, vector<unsigned int> &indices, bool hasVAO)
    {
        if (hasVAO == false) {
            // create buffers/arrays
            glGenVertexArrays(1, &VAO);
            glGenBuffers(1, &VBO);
            glGenBuffers(1, &EBO);
        }

        glBindVertexArray(VAO);
        // load data into vertex buffers
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        // A great thing about structs is that their memory layout is sequential for all its items.
        // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
        // again translates to 3/2 floats which translates to a byte array.
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

        // set the vertex attribute pointers
        // vertex Positions
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
        // vertex normals
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
        // vertex texture coords
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));

        glBindVertexArray(0);
    }

    // Mesh function 2
    void DrawMesh(Shader &shader, unsigned int &VAO, vector<unsigned int> &indices, vector<Texture> &textures)
    {
        shader.setInt("texType", texEnable);
        shader.setInt("texNum", texEnable);
        if (texEnable == 1) {
            shader.setInt("material.texture_diffuse", 0);
        } else if (texEnable == 2) {
            shader.setInt("material.texture_diffuse", 1);
        } else if (texEnable == 3) {
            shader.setInt("material.texture_diffuse", 2);
        }
        shader.setVec3("orgColor", orgColor);

        if (lampType == 1) { // point light
            shader.setInt("texType", 4);
            shader.setVec3("light.position", lightPos);
            shader.setVec3("viewPos", cameraPos);
            // light properties 光线衰减使可视距离为50单位
            shader.setFloat("light.constant", 1.0f);
            shader.setFloat("light.linear", 0.09f);
            shader.setFloat("light.quadratic", 0.032f);
            QVector3D t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("light.ambient", t);
            t = QVector3D(0.8f, 0.8f, 0.8f);
            shader.setVec3("light.diffuse", t);
            t = QVector3D(1.0f, 1.0f, 1.0f);
            shader.setVec3("light.specular", t);
            // material properties
            // 环境光
            shader.setVec3("material.ambient", orgColor);
            // 漫反射
            shader.setVec3("material.diffuse", orgColor);
            // 镜面光 : 作适当弱化
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("material.specular", t);
            // 瞎眼系数
            shader.setFloat("material.shininess", 32.0f);
        } else if (lampType == 2) { // directional light
            shader.setInt("texType", 5);
            QVector3D t = QVector3D(-0.2f, -1.0f, -0.3f);
            shader.setVec3("light.direction", t);
            shader.setVec3("viewPos", cameraPos);
            // light properties 平行光不衰减
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("light.ambient", t);
            t = QVector3D(0.8f, 0.8f, 0.8f);
            shader.setVec3("light.diffuse", t);
            t = QVector3D(1.0f, 1.0f, 1.0f);
            shader.setVec3("light.specular", t);
            // material properties
            // 环境光
            shader.setVec3("material.ambient", orgColor);
            // 漫反射
            shader.setVec3("material.diffuse", orgColor);
            // 镜面光 : 作适当弱化
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("material.specular", t);
            // 瞎眼系数
            shader.setFloat("material.shininess", 32.0f);
        } else if (lampType == 3) { // spot light
            shader.setInt("texType", 6);
            shader.setVec3("light.position", cameraPos);
            shader.setVec3("viewPos", cameraPos);
            // light properties 模拟手电筒
            shader.setVec3("light.direction", cameraFront);
            shader.setFloat("light.cutOff", cos(qDegreesToRadians(12.5f)));
            shader.setFloat("light.outerCutOff", cos(qDegreesToRadians(20.5f)));
            // light properties 光线衰减使可视距离为50单位
            shader.setFloat("light.constant", 1.0f);
            shader.setFloat("light.linear", 0.09f);
            shader.setFloat("light.quadratic", 0.032f);
            QVector3D t = QVector3D(0.1f, 0.1f, 0.1f);
            shader.setVec3("light.ambient", t);
            t = QVector3D(0.8f, 0.8f, 0.8f);
            shader.setVec3("light.diffuse", t);
            t = QVector3D(1.0f, 1.0f, 1.0f);
            shader.setVec3("light.specular", t);
            // material properties
            // 环境光
            shader.setVec3("material.ambient", orgColor);
            // 漫反射
            shader.setVec3("material.diffuse", orgColor);
            // 镜面光 : 作适当弱化
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("material.specular", t);
            // 瞎眼系数
            shader.setFloat("material.shininess", 32.0f);
        }

        // bind appropriate textures
        for(unsigned int i = 0; i < textures.size(); i++)
        {
            glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
            // retrieve texture number (the N in diffuse_textureN)
            string name = textures[i].type;
            glUniform1i(glGetUniformLocation(shader.ID, name.c_str()), i);
            // and finally bind the texture
            glBindTexture(GL_TEXTURE_2D, textures[i].id);
        }

        // draw mesh
        glBindVertexArray(VAO);
        // GL_POINT 点模式
        // GL_LINE 线框模式
        // GL_FILL 面模式
        if (drawType == 1) {
            shader.setInt("texType", 0);
            glEnable(GL_POINT_SMOOTH);
            glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST/*GL_NICEST*/); // 抗锯齿
            glPolygonMode(GL_FRONT, GL_POINT);
            glPolygonMode(GL_BACK, GL_POINT);
        } else if (drawType == 2) {
            shader.setInt("texType", 0);
//            glEnable(GL_LINE_SMOOTH);
//            glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST/*GL_NICEST*/); // 抗锯齿
            glPolygonMode(GL_FRONT, GL_LINE);
            glPolygonMode(GL_BACK, GL_LINE);
        } else if (drawType == 3) {
            glPolygonMode(GL_FRONT, GL_FILL);
            glPolygonMode(GL_BACK, GL_FILL);
        }
        if (clarkLoop == 1) // 1 : clark
            glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_INT, 0);
        else if (clarkLoop == 2) // 2 : loop
            glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // always good practice to set everything back to defaults once configured.
        glActiveTexture(GL_TEXTURE0);
    }

    /*  Model Data */
    vector<Texture> textures_loaded;	// stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once.
    vector<Mesh> meshes;
    string directory;
    bool gammaCorrection;

    /*  Functions   */
    // constructor, expects a filepath to a 3D model.
    Model(string const &path, bool gamma = false) : gammaCorrection(gamma)
    {
        initializeOpenGLFunctions();

        readClarkModel(path);
        //loadModel(path);
    }

    void subdivision() {
        for(unsigned int i = 0; i < meshes.size(); i++) {
            meshes[i].clarkLoop = clarkLoop;
            if (meshes[i].clarkLoop == 1) {
                meshes[i].clarkSubdivision();
            } else if (meshes[i].clarkLoop == 2) {
                meshes[i].loopSubdivision();
            }
        }
    }

    void original() {
        for(unsigned int i = 0; i < meshes.size(); i++) {
            meshes[i].originalMesh();
        }
    }

    // draws the model, and thus all its meshes
    void Draw(Shader &shader)
    {
        for(unsigned int i = 0; i < meshes.size(); i++) {
            meshes[i].clarkLoop = clarkLoop;
            meshes[i].genNormal();
            setupMesh(meshes[i].VAO, meshes[i].VBO, meshes[i].EBO, meshes[i].verticesWithLight, meshes[i].indicesWithLight, meshes[i].hasVAO);
            DrawMesh(shader, meshes[i].VAO, meshes[i].indices, meshes[i].textures);
        }
    }

    void readClarkModel(const std::string& filename) {
        vector<Vertex> vertices;
        vector<unsigned int> indices;
        vector<Texture> textures;

        // type = 1 : clark ; type = 2 : loop
        std::string fileName = filename;
        std::ifstream offFile(fileName.c_str(), std::ios_base::in);
        if (offFile.is_open()) {
            std::string line;
            getline(offFile, line);
            getline(offFile, line);
            std::stringstream ssMeta(line);
            unsigned int numOfVertex, numOfFace, numOfEdge;
            ssMeta >> numOfVertex >> numOfFace >> numOfEdge;
            //printf("%d %d %d\n", numOfVertex, numOfFace, numOfEdge);
            for (unsigned int i = 0; i < numOfVertex; ++i) {
                getline(offFile, line);
                if (line.size() == 0) {
                    i -= 1;
                    continue;
                }
                //printf("%s : ", line.c_str());
                std::stringstream ss(line);
                float x, y, z;
                ss >> x >> y >> z;
                //printf("%f %f %f\n", x, y, z);
                Vertex vertex;
                QVector3D vector;
                vector.setX(x);
                vector.setY(y);
                vector.setZ(z);
                vertex.Position = vector;
                vertex.Normal = QVector3D(0.0f, 0.0f, 0.0f);
                vertex.TexCoords = QVector2D(0.0f, 0.0f);
                vertices.push_back(vertex);
            }
            for (unsigned int i = 0; i < numOfFace; ++i) {
                getline(offFile, line);
                //printf("%s : ", line.c_str());
                if (line.size() == 0) {
                    i -= 1;
                    continue;
                }
                std::stringstream ss(line);
                int edges;
                ss >> edges;
                for (int j = 0; j < edges; ++j) {
                    int v;
                    ss >> v;
                    indices.push_back(v);
                    //printf("%d ", v);
                }
                //printf("\n");
            }
        }

        Mesh newMesh = Mesh(vertices, indices, textures);
        //newMesh.genNormal();
        setupMesh(newMesh.VAO, newMesh.VBO, newMesh.EBO, newMesh.verticesWithLight, newMesh.indicesWithLight, newMesh.hasVAO);
        newMesh.hasVAO = true;
        meshes.push_back(newMesh);
    }

private:


};

#endif // MODEL_H
